package cn.springboot.mybatis.dao.configuration;

import cn.springboot.mybatis.dao.mapper.UserMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * 读配置
 *
 * @author junrui.wang
 * @create 2017/9/8
 */

/**
 * 凡是被Spring管理的类，实现接口 EnvironmentAware
 * 重写方法 setEnvironment 可以在工程启动时，获取到系统环境变量和application配置文件中的变量。
 */
@Configuration
@EnableTransactionManagement
public class MybatisConfiguration{
    @Autowired
    private CustomDataSourceProperties properties;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private UserMapper userMapper;

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public UserMapper userMapper() {
        return sqlSessionTemplate.getMapper(UserMapper.class);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        DataSourceBuilder builder = DataSourceBuilder
                .create(this.properties.getClassLoader())
                .driverClassName(this.properties.getDriver())
                .url(this.properties.getUrl())
                .username(this.properties.getUser())
                .password(this.properties.getPass());
        bean.setDataSource(builder.build());
        ClassPathResource classPathResource = new ClassPathResource("UserMapper.xml");
        //ClassPathResource classPathResource = new ClassPathResource("mybatis-config.xml");
        Resource[] resources = {classPathResource};
        bean.setMapperLocations(resources);
        SqlSessionFactory factory = null;
        try {
            factory = bean.getObject();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return factory;
    }
}
